package com.talkyun.openx.server.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;

public class SessionCleaner {
    private static final Logger logger = LoggerFactory.getLogger(SessionCleaner.class);
    private SessionManager sessionManager = SessionManager.get();
    private long lastLogTime = System.currentTimeMillis();
    private long maxActiveTime;

    public SessionCleaner(long time) {
        this.maxActiveTime = time;
    }

    public void clean() {
        long now = System.currentTimeMillis();

        Set<Map.Entry<String, Session>> all = sessionManager.getAllSession();

        if (now - lastLogTime > 5 * 60 * 1000) {
            lastLogTime = now;
            if (all.size() > 0) {
                logger.info("=> Total session size {}", all.size());
            }
        }

        for (Map.Entry<String, Session> entry : all) {
            Session session = entry.getValue();
            long lastTime = session.getLastActiveTime();
            if (now - lastTime > maxActiveTime) {
                try {
                    this.doClean(session);
                } catch (Throwable t) {
                    logger.error("=> Fail to clean {} ", session.getId(), t);
                }
            }
        }
    }

    private void doClean(Session session) {
        sessionManager.clean(session.getId());
    }
}